#include "TcpServer.h"
#include "Connection.h"

TcpServer::TcpServer(const std::string &ip, const uint16_t port)
{
    acceptor_ = new Acceptor(&loop_, ip, port);
    acceptor_->setnewconnectioncb(std::bind(&TcpServer::newconnection, this, std::placeholders::_1));
    loop_.setepolltimeoutcallback(std::bind(&TcpServer::epolltimeout, this, std::placeholders::_1));
}

TcpServer::~TcpServer()
{
    delete acceptor_;
    for (auto &aa : conns_)
    {
        delete aa.second;
    }
}

void TcpServer::start()
{
    loop_.run();
}

void TcpServer::newconnection(Socket *clientsock)
{
    Connection *conn = new Connection(&loop_, clientsock);
    conn->setclosecallback(std::bind(&TcpServer::closeconnection, this, std::placeholders::_1));
    conn->seterrorcallback(std::bind(&TcpServer::errorconnection, this, std::placeholders::_1));

    conn->sethaddlemsgcallback(std::bind(&TcpServer::haddlemessage, this, std::placeholders::_1, std::placeholders::_2));

    conn->setsendcompletecallback(std::bind(&TcpServer::sendcomplete, this, std::placeholders::_1));

    //printf("New client connected: %s:%d\n", conn->ip().c_str(), conn->port());
    conns_[conn->fd()] = conn;

    if(newconnectioncb_) newconnectioncb_(conn);
}

void TcpServer::closeconnection(Connection *conn)
{
    if(closeconnectioncb_) closeconnectioncb_(conn);
    //printf("client(eventfd=%d)disconnected\n", conn->fd());
    // close(conn->fd());
    conns_.erase(conn->fd());
    delete conn;
}
void TcpServer::errorconnection(Connection *conn)
{
    if(errorconnectioncb_) errorconnectioncb_(conn);
    //printf("else error\n");
    // close(conn->fd());
    conns_.erase(conn->fd());
    delete conn;
}

// 处理数据的逻辑放到这里
void TcpServer::haddlemessage(Connection *conn, std::string& message)
{
    if(onmessagecb_) onmessagecb_(conn,message);
    // message = "replay:" + message; // 回显业务
    // int len = message.size();

    // std::string tmpbuf((char *)&len, 4);
    // tmpbuf.append(message);

    // // write(conn->fd(), tmpbuf.data(), tmpbuf.size());
    // conn->send(tmpbuf.data(), tmpbuf.size());
}

void TcpServer::sendcomplete(Connection *conn)
{
    //printf("send complete\n");
    if(sendcompletecb_) sendcompletecb_(conn);
}

void TcpServer::epolltimeout(EventLoop *loop)
{
    //printf("epoll_wait() timeout\n");

    timeoutcb_(loop);
}

// 设置新连接建立时的回调（参数：Connection指针）
void TcpServer::setNewConnectionCB(std::function<void(Connection *)> fn)
{
    newconnectioncb_ = fn;
}

// 设置连接关闭时的回调（参数：Connection指针）
void TcpServer::setCloseConnectionCB(std::function<void(Connection *)> fn)
{
    closeconnectioncb_ = fn;
}

// 设置连接错误时的回调（参数：Connection指针）
void TcpServer::setErrorConnectionCB(std::function<void(Connection *)> fn)
{
    errorconnectioncb_ = fn;
}

// 设置消息到达时的回调（参数：Connection指针 + 消息内容引用）
void TcpServer::setOnMessageCB(std::function<void(Connection *, std::string &message)> fn)
{
    onmessagecb_ = fn;
}

// 设置数据发送完成时的回调（参数：Connection指针）
void TcpServer::setSendCompleteCB(std::function<void(Connection *)> fn)
{
    sendcompletecb_ = fn;
}

// 设置超时事件回调（参数：EventLoop指针）
void TcpServer::setTimeoutCB(std::function<void(EventLoop *)> fn)
{
    timeoutcb_ = fn;
}